package com.shopping.controller;

import com.alibaba.fastjson.JSONObject;
import com.shopping.constant.ResponseCode;
import com.shopping.pojo.User;
import com.shopping.service.user.UserServiceImpl;
import com.shopping.util.BeanValidator;
import com.shopping.util.WXAppletUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @PostMapping(value = {"/login"})
    public Map<String, Object> login(@RequestBody JSONObject jsonObject, HttpSession session){
        String code = jsonObject.getString("code");
        String avatarUrl = jsonObject.getString("avatarUrl");
        String nickname = jsonObject.getString("nickname");
        System.out.println("---> UserController: ");
        System.out.println("jsonObject: " + jsonObject.toJSONString());
        System.out.println("===> code: " + code);
        System.out.println("===> avatarUrl: " + avatarUrl);
        System.out.println("===> nickname: " + nickname + "\n");

        Map<String, Object> map = new HashMap<>();
        User user = new User();
        Map<String, Object> wxMap = WXAppletUserUtil.getSessionKeyOrOpenid(code);
        if(wxMap.get("openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            map.put("errcode", wxMap.get("errcode"));
            map.put("errmsg", wxMap.get("errmsg"));
            return map;
        }
        user.setOpenid(String.valueOf(wxMap.get("openid")));
        user.setAvatar(avatarUrl);
        user.setNickName(nickname);
        user.setLevel(1);
        return userService.login(user, wxMap);
    }

    @PostMapping(value = {"/user/update"})
    public Map<String, Object> update(User user){
        Map<String, Object> map = new HashMap<>();
        if(!BeanValidator.validate(user)){
            map.put("code",ResponseCode.PARAM_ILLEGAL.getValue());
        }else{
            map = userService.update(user);
        }
        return map;
    }
}
